<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div class="img">
      <!-- 图片，用来展示用户选择的头像 -->
      <img v-if="avatar" :src="avatar" alt="" />
      <img v-else src="~assets/images/avatar.jpg" alt="" />

      <!-- 按钮区域 -->
      <div class="btn-box">
        <input @change="fileInfo" ref="file" style="display: none" type="file" name="" id="" class="file">
        <!-- type="primary" 选取图片 -->
        <el-button @click="$refs.file.click()" type="primary" icon="el-icon-plus">选择图片</el-button>
        <el-button @click="upLoad" type="success" icon="el-icon-upload" :disabled="!avatar">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
import { head } from 'network/login'

export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    fileInfo (e) {
      const files = e.target.files
      // 判断用户是否点击取消
      if (files.length === 0) {
        this.avatar = ''
        return
      }
      // 创建读取文件实例对象
      const fs = new FileReader()
      // 开始读取文件
      fs.readAsDataURL(files[0])
      // 获取读取后的 base64 文件格式
      fs.onload = (e) => {
        // 赋值给当前要渲染的数据
        this.avatar = e.target.result
      }
    },
    async upLoad () {
      const { data: res } = await head({ avatar: this.avatar })
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.$store.dispatch('getUserInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box {
  margin-top: 10px;
}
.preview {
  object-fit: cover;
}

.img img {
  width: 350px;
  height: 350px;
  object-fit: cover;
}
</style>
